package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.commen.Result;
import com.itheima.commen.exception.BusinessException;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {


    //注入userMapper
    @Autowired
    private UserMapper userMapper;

    /**
     * 分页查询所有
     *
     * @return
     */
    @Transactional(readOnly = true)
    public PageInfo<User> getAll(int page,int size) {
        PageHelper.startPage(page,size);

        List<User> userList = userMapper.getAll();

        return new PageInfo<User>(userList);
    }

    /**
     * 查询单个
     *
     * @return
     */
    @Transactional(readOnly = true)
    public User get(int id) {
        return userMapper.get(id);
    }

    /**
     * 新增操作
     *
     * @param user
     * @return
     */
    @Override
    public boolean save(User user) {
        return userMapper.save(user);
    }

    /**
     * 批量删除
     *
     * @param uuids
     * @return
     */
    @Override
    public boolean deleteByUuids(String uuids) {
        if(uuids != null && uuids.length()>0){
            String[] ids = uuids.split(",");
            return userMapper.deleteByUuids(ids);
        }
        return false;

    }

    /**
     * 修改操作
     *
     * @param user
     * @return
     */
    @Override
    public boolean update(User user) {
        return userMapper.update(user);
    }

    /**
     * 登录验证
     *
     * @param userName
     * @param password
     * @return
     */
    public User login(String userName, String password) {
        if (StringUtils.isBlank(userName)){
            throw  new BusinessException(new Result("用户名不能为空"));
        }
        if (StringUtils.isBlank(password)){
            throw  new BusinessException(new Result("密码不能为空"));
        }

        User user = userMapper.getUsernameAndPassword(userName, password);
        if (user == null){
            throw  new BusinessException(new Result("用户名或者密码错误"));
        }
        return user;
    }

    /**
     * 分页条件查询
     *
     * @param user
     * @return
     */
    @Transactional(readOnly = true)
    public PageInfo<User> getUsers(User user,int page,int size) {
        PageHelper.startPage(page,size);

        List<User> users = userMapper.getUsers(user);
        return new PageInfo<User>(users);
    }
}
